import axios from 'axios';

// API配置
const API_CONFIG = {
  BASE_URL: 'http://172.16.4.151:1122/facetnet',
  // 修改为Next.js API路由
  TIMEOUT: 30000,
};

// 创建axios实例
const service = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  }
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 根据请求类型构造参数
    if (config.method === 'get') {
      config.params = { 
        ...config.params,
        path: config.url // 将原始路径作为参数传递
      };
      config.url = ''; // 清空url，使用base url
    } else {
      // POST请求将路径和数据一起传递
      config.data = {
        path: config.url,
        data: config.data
      };
      config.url = ''; // 清空url，使用base url
    }
    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    console.error('响应错误:', error);
    return Promise.reject(error);
  }
);

// 导出请求方法
export const request = {
  get: (url, params = {}) => {
    return service.get(url, { params });
  },

  post: (url, data = {}, config = {}) => {
    return service.post(url, data, config);
  },

  put: (url, data = {}) => {
    return service.put(url, data);
  },

  delete: (url, params = {}) => {
    return service.delete(url, { params });
  }
};

// 导出错误处理工具
export const handleApiError = (error) => {
  if (error.response) {
    const status = error.response.status;
    const message = error.response.data?.message || '服务器错误';
    return `HTTP错误 ${status}: ${message}`;
  } else if (error.request) {
    return '无法连接到服务器，请检查网络连接';
  } else {
    return `请求错误: ${error.message}`;
  }
}; 